package com.aisile.common.aliyun.scan;

import com.aisile.common.exception.CustomExceptionCatch;
import com.aisile.model.common.enums.WemediaHttpCodeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @Auther:yry
 * @Date:2024/1/9 0009
 * @VERSON:1.0
 */
@Setter
@Component
@PropertySource("classpath:aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
public class GreenTextForContentScan {
    private String accesskey;
    private String secretkey;
    private String endpoint;

    public Integer textScan(List<String> contents)  {
        try {
            DefaultProfile profile = DefaultProfile.getProfile(
                    endpoint, accesskey, secretkey);
            DefaultProfile.addEndpoint(endpoint, "Green", "green." + endpoint + ".aliyuncs.com");
            // 注意：此处实例化的client尽可能重复使用，提升检测性能。避免重复建立连接。
            IAcsClient client = new DefaultAcsClient(profile);
            TextScanRequest textScanRequest = new TextScanRequest();
            textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
            textScanRequest.setHttpContentType(FormatType.JSON);
            textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
            textScanRequest.setEncoding("UTF-8");
            textScanRequest.setRegionId(endpoint);

            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();

            for (String item : contents) {
                Map<String, Object> task1 = new LinkedHashMap<String, Object>();
                task1.put("dataId", UUID.randomUUID().toString());
                /**
                 * 待检测的文本，长度不超过10000个字符。
                 */
                task1.put("content", item);
                tasks.add(task1);
            }

            JSONObject data = new JSONObject();

            /**
             * 检测场景。文本垃圾检测请传递antispam。
             **/
            data.put("scenes", Arrays.asList("antispam"));
            data.put("tasks", tasks);
            System.out.println(JSON.toJSONString(data, true));
            textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            // 请务必设置超时时间。
            textScanRequest.setConnectTimeout(3000);
            textScanRequest.setReadTimeout(6000);

            HttpResponse httpResponse = client.doAction(textScanRequest);
            if (!httpResponse.isSuccess()) {
                System.out.println("response not success. status:" + httpResponse.getStatus());
                // 业务处理。
                CustomExceptionCatch.catchWemedia(WemediaHttpCodeEnum.DATA_NOT_EXIST);
            }
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
            System.out.println(JSON.toJSONString(scrResponse, true));
            if (200 != scrResponse.getInteger("code")) {
                System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                // 业务处理。
                CustomExceptionCatch.catchWemedia(WemediaHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 定义分值   最正确  不动    失败 -分    疑似 + 分
            int score = 0;
            int total = contents.size() + 1;
            JSONArray taskResults = scrResponse.getJSONArray("data");
            for (Object taskResult : taskResults) {
                if (200 != ((JSONObject) taskResult).getInteger("code")) {
                    System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                    // 业务处理。
                    continue;
                }
                JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                for (Object sceneResult : sceneResults) {
                    String scene = ((JSONObject) sceneResult).getString("scene");
                    String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                    Float rate = ((JSONObject) sceneResult).getFloat("rate");
                    // 根据scene和suggestion做相关处理。
                    // suggestion为pass表示未命中垃圾。suggestion为block表示命中了垃圾，可以通过label字段查看命中的垃圾分类。
                    System.out.println("args = [" + scene + "]");
                    System.out.println("args = [" + suggestion + "]");
                    if (suggestion.equals("block")) {
                        // 失败 恒定负值
                        score = score - total;
                    }
                    if (suggestion.equals("review")) {
                        if (rate >= 85) {
                            score++;
                        } else {
                            //失败
                            score = score - total;
                        }
                    }
                    if (suggestion.equals("pass")) {
                        if (rate < 90) {  // 自定公司定义的区间
                            score++;
                        }
                    }
                }
            }
            return score;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
